package com.my.main.controller.userAndRight;

import com.github.pagehelper.StringUtil;
import com.my.main.entity.userAndRight.*;
import com.my.main.base.controller.BaseController;
import com.my.main.base.entity.Result;
import com.my.main.base.entity.ResultCode;
import com.my.main.common.utils.CurrencyUtil;
import com.my.main.common.utils.ValidataUtil;
import com.my.main.service.userAndRight.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 角色管理
 *
 * @author wuh 2020-05-12
 */
@CrossOrigin
@RestController
@RequestMapping(value="/api/v1/sys/role")
public class SysRightsRoleController extends BaseController {


    @Autowired
    private SysRightsRoleService sysRightsRoleService;
    // 角色与用户关系
    @Autowired
    private SysRightsRoleUserRelationService sysRightsRoleUserRelationService;
    // 第三方角色权限
    @Autowired
    private SysRightsRoutersService sysRightsRoutersService;
    @Autowired
    private SysRightsRoleRoutersService sysRightsRoleRoutersService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 条件查询角色列表
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 查询角色列表")
    @RequestMapping(value="/queryRoleList", method = RequestMethod.POST)
    public Result queryRoleList(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("page", map.get("page"));
        resMap.put("limit", map.get("limit"));

        try {
            // 查询总条数
            resMap.put("totalCount", sysRightsRoleService.queryCount());

            List<Map<String, Object>> resList = new ArrayList<>();

            map.put("page", CurrencyUtil.PageRowNum(Integer.parseInt(map.get("page").toString()), Integer.parseInt(map.get("limit").toString())));
            List<SysRightsRole> roleList = sysRightsRoleService.queryList(map);
            for(SysRightsRole role_t : roleList) {
                Map<String, Object> map_t = new HashMap<String, Object>();
                map_t.put("roleId", role_t.getRoleId());
                map_t.put("roleName", role_t.getName());
                map_t.put("userNum", sysUserService.queryUserByRoleId(role_t.getRoleId()).size());
                map_t.put("isAdmin", role_t.getIsAdmin());
                resList.add(map_t);
            }
            resMap.put("roleList", resList);
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 通过角色ID查询角色信息
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 查询角色")
    @RequestMapping(value="/queryRole", method = RequestMethod.POST)
    public Result queryRole(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();

        try {
            SysRightsRole role = sysRightsRoleService.queryStringId(map.get("roleId").toString());
            resMap.put("roleId", role.getRoleId());
            resMap.put("name", role.getName());
            resMap.put("isAdmin", role.getIsAdmin());
            resMap.put("sort", role.getSort());

            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 创建角色
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 新增角色")
    @RequestMapping(value="/saveRole", method = RequestMethod.POST)
    public Result saveRole(@RequestBody Map<String, Object> map) {
        if (StringUtil.isEmpty(map.get("name").toString())) {
            return new Result(ResultCode.FAIL, "请填写角色名称");
        }
        if (StringUtil.isEmpty(map.get("sort").toString()) || !ValidataUtil.validataNumber(map.get("sort"), 0)) {
            return new Result(ResultCode.FAIL, "请填写排序值");
        }
        if (StringUtil.isEmpty(map.get("isAdmin").toString())) {
            return new Result(ResultCode.FAIL, "请选择是否是超级管理员");
        }

        try {
            SysRightsRole role = new SysRightsRole();
            role.setRoleId(idWorker.nextId() + "");
            role.setName(map.get("name").toString());
            role.setSort(Integer.parseInt(map.get("sort").toString()));
            role.setIsAdmin(Boolean.parseBoolean(map.get("isAdmin").toString()));
            role.setAddIp(requestUtil.getIp());
            role.setAddUserId(userInfo.getUserId());
            role.setLastEditIp(requestUtil.getIp());
            role.setLastEditBy(userInfo.getUserId());
            role.setIsDel(false);

            sysRightsRoleService.isSave(role);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 修改角色
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 修改角色")
    @RequestMapping(value="/updateRole", method = RequestMethod.POST)
    public Result updateRole(@RequestBody Map<String, Object> map) {
        if (StringUtil.isEmpty(map.get("roleId").toString())) {
            return new Result(ResultCode.FAIL, "请选择角色");
        }
        if (StringUtil.isEmpty(map.get("name").toString())) {
            return new Result(ResultCode.FAIL, "请填写角色名称");
        }
        if (StringUtil.isEmpty(map.get("sort").toString()) || !ValidataUtil.validataNumber(map.get("sort"), 0)) {
            return new Result(ResultCode.FAIL, "请填写排序值");
        }
        if (StringUtil.isEmpty(map.get("isAdmin").toString())) {
            return new Result(ResultCode.FAIL, "请选择是否是超级管理员");
        }

        try {
            SysRightsRole role = sysRightsRoleService.queryStringId(map.get("roleId").toString());
            role.setName(map.get("name").toString());
            role.setSort(Integer.parseInt(map.get("sort").toString()));
            role.setIsAdmin(Boolean.parseBoolean(map.get("isAdmin").toString()));
            role.setLastEditIp(requestUtil.getIp());
            role.setLastEditBy(userInfo.getUserId());

            sysRightsRoleService.isUpdate(role);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }

    /**
     * 变更角色类型（是否是超级管理员）
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 变更角色类型")
    @RequestMapping(value="/changeRoleType", method = RequestMethod.POST)
    public Result changeRoleType(@RequestBody Map<String, Object> map) {
        if (StringUtil.isEmpty(map.get("roleId").toString())) {
            return new Result(ResultCode.FAIL, "请选择角色");
        }
        if (StringUtil.isEmpty(map.get("isAdmin").toString())) {
            return new Result(ResultCode.FAIL, "请选择是否是超级管理员");
        }

        try {
            SysRightsRole role = sysRightsRoleService.queryStringId(map.get("roleId").toString());
            role.setIsAdmin(Boolean.parseBoolean(map.get("isAdmin").toString()));
            role.setLastEditIp(requestUtil.getIp());
            role.setLastEditBy(userInfo.getUserId());

            sysRightsRoleService.isUpdate(role);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 删除角色
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 删除角色")
    @RequestMapping(value="/deleteRole", method = RequestMethod.POST)
    public Result deleteRole(@RequestBody Map<String, Object> map) {
        if (StringUtil.isEmpty(map.get("roleId").toString())) {
            return new Result(ResultCode.FAIL, "请选择角色");
        }

        try {
            SysRightsRole role = sysRightsRoleService.queryStringId(map.get("roleId").toString());
            if(role == null) {
                return new Result(ResultCode.FAIL, "角色不存在");
            }

            sysRightsRoleService.isDeleteRole(role);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 获取全部路由列表
     *
     * @return
     */
    @ApiOperation(value="用户与权限 - 获取全部路由列表", tags = NOINTERCEPT)
    @RequestMapping(value="/queryUserPerimmionInfo", method = RequestMethod.POST)
    public Result queryUserPerimmionInfo() {
        Map<String, Object> sqlMap = new HashMap<>();

        try {
            // 1.获取用户id
            String userId = null;
            List<String> routerIdList = new ArrayList<>();
            userId = userInfo.getUserId();

            // 2.查询用户角色
            Map<String, Object> queryMap = new HashMap<String, Object>();
            queryMap.put("userId", userId);
            queryMap.put("limit", 0);
            List<SysRightsRoleUserRelation> srrurList = sysRightsRoleUserRelationService.queryListByMap(queryMap);
            // 3.根据角色查角色与资源关联
            for (SysRightsRoleUserRelation srrur : srrurList) {
                Map<String, Object> srrurMap = new HashMap<String, Object>();
                srrurMap.put("roleId", srrur.getRoleId());
                List<SysRightsRoleRouters> list = sysRightsRoleRoutersService.queryList(srrurMap);
                if (list.size() > 0) {
                    for (SysRightsRoleRouters sysRightsRoleRouters : list) {
                        routerIdList.add(sysRightsRoleRouters.getRouterId());
                    }
                }
            }

            // 获取路由列表
            sqlMap.clear();
            sqlMap.put("parentId", 0);
            if (routerIdList.size() > 0) {
                sqlMap.put("routerIdList", routerIdList);
            } else {
                routerIdList.add("-1");
                sqlMap.put("routerIdList", routerIdList);
            }
            List<Map<String, Object>> roles = quertChildRoute1(sqlMap);

            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("roles", roles);
            resultMap.put("name", userInfo.getUsername());
            resultMap.put("realName", userInfo.getRealName());
            SysUser sysUser = sysUserService.queryStringId(userInfo.getUserId());
            resultMap.put("avatar", sysUser == null ? "" : sysUser.getHead());
            resultMap.put("userId", userInfo.getUserId());
            resultMap.put("isAdmin", userInfo.getIsAdmin());
            return new Result(ResultCode.SUCCESS, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 获取菜单路由权限
     *
     * @author mengft    2020-07-17
     */
    @ApiOperation(value="用户与权限 - 获取菜单路由权限")
    @RequestMapping(value="/querySysRightsRoutersListForRole", method = RequestMethod.POST)
    public Result querySysRightsRoutersListForRole() {
        Map<String, Object> sqlmap = new HashMap<>();

        try {
            sqlmap.clear();
            sqlmap.put("parentId", "0");
            List<Map<String, Object>> list = quertChildRoute(sqlmap);

            return new Result(ResultCode.SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 递归查询资源路径
     *
     * @param sqlMap(parentId: 路由id)
     */
    private List<Map<String, Object>> quertChildRoute(Map<String, Object> sqlMap) {
        List<Map<String, Object>> sysDepartmentList = new ArrayList<>();

        List<SysRightsRouters> sysRightsRouters_t = sysRightsRoutersService.queryList(sqlMap);
        for(SysRightsRouters sysRightsRouters: sysRightsRouters_t) {
            Map<String, Object> routersMap = new HashMap<>();
            routersMap.put("id", sysRightsRouters.getRouterId());
            routersMap.put("name", sysRightsRouters.getTitle());
            routersMap.put("checked", true);
            routersMap.put("path", sysRightsRouters.getPath());

            sqlMap.put("parentId", sysRightsRouters.getRouterId());
            List<Map<String,Object>> children = quertChildRoute(sqlMap);
            if (children!=null && children.size()>0) {
                routersMap.put("children", children);
            }
            sysDepartmentList.add(routersMap);
        }

        return sysDepartmentList;
    }


    /**
     * 递归查询资源路径
     *
     * @param sqlMap(parentId: 路由id)
     */
    private List<Map<String, Object>> quertChildRoute1(Map<String, Object> sqlMap) {
        List<Map<String, Object>> sysDepartmentList = new ArrayList<>();

        List<SysRightsRouters> sysRightsRouters_t = sysRightsRoutersService.queryList(sqlMap);
        for(SysRightsRouters sysRightsRouters: sysRightsRouters_t) {
            Map<String, Object> routersMap = new HashMap<>();
            routersMap.put("routerId", sysRightsRouters.getRouterId());
            routersMap.put("title", sysRightsRouters.getTitle());
            routersMap.put("routerKey", sysRightsRouters.getRouterKey());
            routersMap.put("path", sysRightsRouters.getPath());
            routersMap.put("isHide", sysRightsRouters.getIsHide());
            routersMap.put("type", sysRightsRouters.getType());
            routersMap.put("icon", sysRightsRouters.getIcon());
            routersMap.put("sort", sysRightsRouters.getSort());

            sqlMap.put("parentId", sysRightsRouters.getRouterId());
            List<Map<String,Object>> children = quertChildRoute1(sqlMap);
            if (children!=null && children.size()>0) {
                routersMap.put("children", children);
            }
            sysDepartmentList.add(routersMap);
        }

        return sysDepartmentList;
    }




}
